<?php
$pageTitle = '查找男友';
require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../classes/User.php';
require_once '../../classes/Friend.php';
require_once '../../config/database.php';

// 检查用户是否登录
if (!isLoggedIn()) {
    setFlashMessage('error', '请先登录');
    redirect(SITE_URL . '/login.php');
}

// 确保用户ID是整数类型
$userId = (int)$_SESSION['user_id'];
$friend = new Friend();
$results = [];
$keyword = '';

// 获取数据库实例
$db = Database::getInstance();


// 处理搜索请求
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['keyword']) && !empty($_GET['keyword'])) {
    $keyword = sanitizeInput($_GET['keyword']);
    
    try {
        // 使用简化的查询
        $results = $db->fetchAll(
            "SELECT id, username, nickname, avatar, email FROM users 
             WHERE (username LIKE ? OR nickname LIKE ? OR email = ?) 
             AND id != ?
             ORDER BY username
             LIMIT 20",
            ["%$keyword%", "%$keyword%", $keyword, $userId]
        );
        
        // 如果没有结果，尝试精确匹配
        if (empty($results)) {
            $results = $db->fetchAll(
                "SELECT id, username, nickname, avatar, email FROM users 
                 WHERE (username = ? OR nickname = ? OR email = ?)
                 AND id != ?
                 ORDER BY username
                 LIMIT 20",
                [$keyword, $keyword, $keyword, $userId]
            );
        }
    } catch (Exception $e) {
        // 如果查询出错，返回空数组
        $results = [];
    }
    
    // 获取男友关系状态
    if (!empty($results)) {
        foreach ($results as &$user) {
            $status = $friend->getFriendshipStatus($userId, $user['id']);
            $user['friendship_status'] = $status ? $status : 'none';
        }
        // 确保引用被释放
        unset($user);
    }
}

include '../../includes/header.php';
?>

<div class="container py-4">
    <div class="row justify-content-center">
        <div class="col-lg-8 mx-auto">
            <div class="card shadow-sm">
                <div class="card-body">
                    <?php if (isset($_SESSION['flash_message'])): ?>
                        <div class="alert alert-<?php echo $_SESSION['flash_type']; ?> alert-dismissible fade show">
                            <?php echo $_SESSION['flash_message']; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                        <?php unset($_SESSION['flash_message'], $_SESSION['flash_type']); ?>
                    <?php endif; ?>
                    
                    <form method="GET" action="" class="mb-4">
                        <div class="input-group">
                            <input type="text" class="form-control" name="keyword" placeholder="请在这里输入" value="<?php echo htmlspecialchars($keyword); ?>" required>
                            <button class="btn btn-primary" type="submit">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                        </div>
                    </form>
                    
                    <?php if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['keyword']) && !empty($_GET['keyword'])): ?>
                        <?php if (empty($results)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-search fa-3x text-muted mb-3"></i>
                                <p class="lead">没有找到匹配 "<?php echo htmlspecialchars($keyword); ?>" 的用户</p>
                            </div>
                        <?php else: ?>
                            <h6 class="mb-3">搜索结果：</h6>
                            <div class="list-group">
                                <?php foreach ($results as $user): ?>
                                    <div class="list-group-item">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <div class="d-flex align-items-center">
                                                <img src="<?php echo getUserAvatar($user['avatar']); ?>" class="rounded-circle me-3" width="50" height="50" alt="<?php echo htmlspecialchars($user['nickname'] ?: $user['username']); ?>">
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($user['nickname'] ?: $user['username']); ?></h6>
                                                    <small class="text-muted">用户名: <?php echo htmlspecialchars($user['username']); ?></small>

                                                </div>
                                            </div>
                                            <div>
                                                <?php if ($user['friendship_status'] === 'accepted'): ?>
                                                    <span class="badge bg-success"><i class="fas fa-check"></i> 已是男友</span>
                                                <?php elseif ($user['friendship_status'] === 'pending'): ?>
                                                    <?php 
                                                    $db = Database::getInstance();
                                                    $pendingRequest = $db->fetch("SELECT * FROM friendships WHERE user_id = ? AND friend_id = ? AND status = 'pending'", [$userId, $user['id']]);
                                                    if ($pendingRequest): 
                                                    ?>
                                                        <span class="badge bg-warning"><i class="fas fa-clock"></i> 请求已发送</span>
                                                    <?php else: ?>
                                                        <span class="badge bg-info"><i class="fas fa-envelope"></i> 等待您接受</span>
                                                        <a href="<?php echo SITE_URL; ?>/views/friend/request.php" class="btn btn-sm btn-outline-primary ms-2">查看请求</a>
                                                    <?php endif; ?>
                                                <?php elseif ($user['friendship_status'] === 'rejected'): ?>
                                                    <form method="POST" action="<?php echo SITE_URL; ?>/api/friend/add.php">
                                                        <input type="hidden" name="friend_id" value="<?php echo $user['id']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-primary">
                                                            <i class="fas fa-user-plus"></i> 再次添加
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <form method="POST" action="<?php echo SITE_URL; ?>/api/friend/add.php">
                                                        <input type="hidden" name="friend_id" value="<?php echo $user['id']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-primary">
                                                            <i class="fas fa-user-plus"></i> 添加男友
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="fas fa-users fa-3x text-muted mb-3"></i>
                            <p class="lead">输入关键词搜索用户</p>
                            <p class="text-muted">可以通过用户名、昵称或邮箱查找</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include '../../includes/footer.php'; ?>
